package com.zhangt.sqlSession;

import com.zhangt.pojo.Configuration;
import com.zhangt.pojo.MappedStatement;

import java.lang.reflect.*;
import java.util.List;

public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws Exception {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement statement = configuration.getMappedStatementMap().get(statementId);
        List<Object> listObj = simpleExecutor.query(configuration, statement, params);
        return (List<E>) listObj;
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws Exception {

        List<Object> objects = selectList(statementId, params);
        if (objects.size() == 1) {
            return (T) objects.get(0);
        } else {
            throw new RuntimeException("");
        }
    }

    @Override
    public int update(String statementId, Object... params) throws Exception {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement statement = configuration.getMappedStatementMap().get(statementId);
        return simpleExecutor.doDelete(configuration, statement,params);
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {

        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, (proxy, method, args) -> {

            String methodName = method.getName();
            String className = method.getDeclaringClass().getName();
            String statementId = className + "." + methodName;
            Type genericReturnType = method.getGenericReturnType();
            switch (configuration.getMappedStatementMap().get(statementId).getCommandType()) {
                case "select":
                    if(genericReturnType instanceof ParameterizedType) {
                        return selectList(statementId, args);
                    }
                    return selectOne(statementId, args);
                default:
                    return update(statementId, args);
            }
        });
        return (T) proxyInstance;
    }
}
